<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>图片在线转换工具</title>
		<style type="text/css">
			.box {
				width: 100%;

			}

			.file {
				width: 1100px;
				margin: 0 auto;
				font-size: 16px;
				color: #666666;
			}

			.title {
				text-align: center;
				height: 60px;
				line-height: 60px;
				border-bottom: 1px solid #ddd;
			}

			.ite {
				margin-bottom: 18px;
			}

			.ite select {
				height: 26px;
				line-height: 26px;
				border: 1px solid #888;
			}

			button {
				border: 0;
				background: #409eff;
				color: #fff;
				padding: 8px 15px;
				cursor: pointer;
				border-radius: 2px;
			}

			button:hover {
				box-shadow: 0 0 8px 0 rgb(232 237 250 / 60%), 0 2px 4px 0 rgb(232 237 250 / 50%);
				opacity: .8;
			}

			.fie img {
				max-width: 700px;
			}
		</style>
	</head>
	<body>
		<div class="box">
			<h2 class="title">在线图片webp/png/jpeg格式转换工具</h2>
			<div class="file">
				<div class="ite">
					<span>选择图片：</span><input type="file" id="inputimg">
				</div>
				<div class="ite">
					<span>选择格式：</span>
					<select id="myselect">
						<option value="1">webp格式</option>
						<option value="2">jpeg格式</option>
						<option value="3">png格式</option>
					</select>
				</div>

				<button id="start">开始转换</button>
				<p>预览：</p>
				<div class="fie">
					<img id="imgShow" src="" alt="">
				</div>
				
				<div class="info">
					<h4>备注：</h4>
					<p>1、转换后的图片请选择右键保存！</p>
					<p>2、该工具目前仅支持转换为webp、jpeg、png的格式。如果是gif动态图片转换后不保留动态效果。</p>
					<p>3、请使用高版本浏览器,推荐使用Chrome。</p>
				</div>
			</div>



		</div>
	</body>

	<script type="text/javascript">
		/*事件*/
		document.getElementById('start').addEventListener('click', function() {
			getImg(function(image) {
				var can = imgToCanvas(image),
					imgshow = document.getElementById("imgShow");
				imgshow.setAttribute('src', canvasToImg(can));
			});
		});
		// 把image 转换为 canvas对象 
		function imgToCanvas(image) {
			var canvas = document.createElement("canvas");
			canvas.width = image.width;
			canvas.height = image.height;
			canvas.getContext("2d").drawImage(image, 0, 0);
			return canvas;
		}
		//canvas转换为image
		function canvasToImg(canvas) {
			var array = ["image/webp", "image/jpeg", "image/png"],
				type = document.getElementById('myselect').value - 1;
			var src = canvas.toDataURL(array[type]);
			return src;
		}
		//获取图片信息
		function getImg(fn) {
			var imgFile = new FileReader();
			try {
				imgFile.onload = function(e) {
					var image = new Image();
					image.src = e.target.result; //base64数据 
					image.onload = function() {
						fn(image);
					}
				}
				imgFile.readAsDataURL(document.getElementById('inputimg').files[0]);
			} catch (e) {
				console.log("请上传图片！" + e);
			}
		}
	</script>
</html>
